<template>
  <!-- #ifndef H5 -->
  <tm-navbar title="浙里资产"></tm-navbar>
  <!-- #endif -->
  <tm-sheet :margin="[0, 0]" :padding="[0, 0]">
    <tm-tabs
      showTabsLineAni
      :list="applyList"
      :item-width="375"
      :default-name="active"
      active-color="#366EF4"
      :width="750"
      :showTabsLine="true"
      @change="tabChanged"
    >
    </tm-tabs>
  </tm-sheet>
  <tm-scrolly
    class="from-content"
    :_style="'height:100%'"
    v-if="active === 'apply'"
  >
    <!-- <primaryForm :formInfo="PrimaryData"></primaryForm>
    <DetailForm :formInfo="DetailData"></DetailForm> -->
    <appFromView :formInfo="formData"></appFromView>
    <tm-form :margin="[0]" :padding="[10]" _class="remark_mr">
      <tm-form-item>
        <tm-input
          :inputPadding="[20]"
          placeholder="请填写审批意见"
          :height="200"
          :model-value="remark"
          @input="changeData($event)"
          confirm-hold
          showCharNumber
          :border="1"
          color="grey-5"
          type="textarea"
        ></tm-input>
      </tm-form-item>
    </tm-form>
  </tm-scrolly>

  <view class="flex flex-row to-bottom" v-if="active === 'apply'">
    <view class="btnItem mr10">
      <tm-button
        :shadow="0"
        text
        form-type="reset"
        class="btnItem"
        label="存为草稿"
        block
        :transprent="true"
        color="#DCDCDC"
        outlined
        fontColor="black"
      ></tm-button>
    </view>
    <view class="btnItem">
      <tm-button
        form-type="submit"
        label="提交审批"
        block
        class="btnItem"
        @click="submit"
      ></tm-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import { getCurrentInstance, ref } from 'vue'
import appFromView from '../work/components/applyFormView/index.vue'
import { model } from '@/ts/base'
import OrgCtrl from '@/ts/controller'
import { applyList } from '../work/config'
import * as dayjs from '../../tmui/tool/dayjs/esm/index'
const DayJs = dayjs.default

const active = ref('apply')
const remark = ref('')
let workData: any = {}
onLoad(() => {
  const instance: any = getCurrentInstance()?.proxy
  const eventChannel = instance.getOpenerEventChannel()
  eventChannel.on('workDetail', async function (data: any) {
    workData = data
    makeWorkForms(data)
  })
})

const formData: any = ref([])
async function makeWorkForms(data: any) {
  formData.value = await getApplyData(data)
}
async function getApplyData(data: any) {
  const node = await data?.loadNode()
  const instance: model.InstanceDataModel = {
    data: {},
    node: node,
    fields: {},
    primary: {},
    rules: []
  }
  if (data.primaryForms.length > 0) {
    for (const form of data.primaryForms) {
      instance.fields[form.id] = await form.loadFields()
      instance.data[form.id] = [
        {
          nodeId: node.id,
          formName: form.name,
          before: [],
          after: [],
          creator: OrgCtrl.user.id,
          createTime: DayJs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          rules: []
        }
      ]
    }
  }
  if (data.detailForms.length > 0) {
    for (const form of data.detailForms) {
      instance.fields[form.id] = await form.loadFields()
      instance.data[form.id] = [
        {
          nodeId: node.id,
          formName: form.name,
          before: [],
          after: [],
          creator: OrgCtrl.user.id,
          createTime: DayJs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          rules: []
        }
      ]
    }
  }
  const apply = data.createApply(undefined, instance)
  return apply
}
async function submit() {
  const FormMap: Map<string, model.FormEditData> = new Map([])
  const mainId: any = []
  const detailId: any = []
  workData.node.forms.forEach((item: { typeName: string; id: any }) => {
    if (item.typeName === '主表') {
      mainId.push(item.id)
    }
  })
  workData.node.forms.forEach((item: { typeName: string; id: any }) => {
    if (item.typeName === '子表') {
      detailId.push(item.id)
    }
  })
  mainId.forEach((item: string) => {
    const mainForm: model.FormEditData = {
      before: [],
      after: formData.value.instanceData?.data[item].at(-1).after || [],
      nodeId: formData.value.instanceData.node!.id,
      creator: OrgCtrl.user.id,
      formName: '',
      createTime: DayJs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
      rules: []
    }
    FormMap.set(item, mainForm)
  })
  detailId.forEach((item: string) => {
    const deatilForm: model.FormEditData = {
      before: [],
      after: formData.value.instanceData?.data[item].at(-1).after || [],
      nodeId: formData.value.instanceData.node!.id,
      creator: OrgCtrl.user.id,
      createTime: DayJs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
      formName: '',
      rules: []
    }
    FormMap.set(item, deatilForm)
  })
  // if(formData.value.validationData()) {
  const res = await formData.value.createApply(
    formData.value.belong.id,
    remark.value,
    FormMap,
    new Map([])
  )
  if (res) {
    uni.showToast({
      title: '提交成功',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 500)
  }
  // }else{
  //   uni.showToast({
  //     title:'请完善表单内容再提交!',
  //     icon: 'none'
  //   })
  // }
}

function tabChanged(data: string) {
  active.value = data
}

function changeData(data: any) {
  remark.value = data
}
</script>

<style lang="scss">
.to-bottom {
  padding: 0px 10px;
  background-color: #fff;
  height: 80px;
  justify-content: flex-end;
  border-top: 1px solid #f7f7f7;
}
.from-content {
  height: calc(100vh - 10px);
  overflow-y: scroll;
}
.mr10 {
  margin-right: 10px;
}
.required::after {
  content: '*';
  display: inline-block;
  color: #d54941;
  font-size: 14px;
  margin-left: 2px;
}
.btnItem {
  width: 120px;
}
</style>
